#ifndef THREAD_SAFE_QUEUE_H
#define THREAD_SAFE_QUEUE_H

#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>

// C++11 兼容的 optional 实现
template <typename T>
class optional
{
public:
    optional() : has_value_(false) {}
    optional(T value) : has_value_(true), value_(std::move(value)) {}

    explicit operator bool() const { return has_value_; }
    const T &operator*() const { return value_; }
    T &operator*() { return value_; }

private:
    bool has_value_;
    T value_;
};

template <typename T>
class ThreadSafeQueue
{
public:
    void push(T value)
    {
        std::lock_guard<std::mutex> lock(mutex_);
        queue_.push(std::move(value));
        cond_.notify_one();
    }

    optional<T> pop()
    {
        std::unique_lock<std::mutex> lock(mutex_);
        cond_.wait(lock, [this]
                   { return done_ || !queue_.empty(); });
        if (done_ && queue_.empty())
            return optional<T>{};

        T value = std::move(queue_.front());
        queue_.pop();
        return optional<T>(std::move(value));
    }

    void set_done()
    {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            done_ = true;
        }
        cond_.notify_all();
    }

    bool empty() const
    {
        std::lock_guard<std::mutex> lock(mutex_);
        return queue_.empty();
    }

private:
    mutable std::mutex mutex_;
    std::queue<T> queue_;
    std::condition_variable cond_;
    bool done_ = false;
};

#endif // THREAD_SAFE_QUEUE_H